package com.zhaoyang.test.jdbcTemplate;

import com.zhaoyang.util.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author 赵扬
 * @time 2020/4/27 08:46
 */
public class JdbcTemplateDemo02 {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * update 执行DML语句
     */
    @Test
    public void test01() {
        String sql = "update emp set salary=10000 where id=1";
        int cnt = template.update(sql);
        System.out.println(cnt);
    }

    @Test
    public void test02() {
        String sql = "insert into emp(id,name) values(null,?)";
        int cnt = template.update(sql, "宋江");
        System.out.println(cnt);
    }

    @Test
    public void test03() {
        String sql = "delete from emp where name = ?";
        int cnt = template.update(sql, "宋江");
        System.out.println(cnt);
    }

    @Test
    public void test04() {
        String sql = "select * from emp where id =?";
        // 查询的结果集长度只能是1
        Map<String, Object> map = template.queryForMap(sql, 100);
        System.out.println(map);
    }

    @Test
    public void test05() {
        String sql = "select * from emp";

        List<Map<String, Object>> maps = template.queryForList(sql);
        System.out.println(maps);

    }

    @Test
    public void test06() {
        String sql = "select * from emp";

        List<Emp> emps = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : emps) {
            System.out.println(emp);
        }
    }

    @Test
    public void test07() {
        String sql = "select count(id) from emp";
        // 多用于聚合函数
        Long aLong = template.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }

}
